/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package generatorGraphics.graphics;

import grammaticalClasses.nwConsole.ShowMote;
import grammaticalClasses.nwConsole.ShowStatCur;
import grammaticalClasses.nwConsole.ShowStatDay;
import grammaticalClasses.nwConsole.ShowStatShort;
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.SeriesException;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import softwareControl.SearchCommands;

/**
 *
 * @author Heitor
 */
public class MoteLatency implements GraphInterface {
    
        
    /**
     * Variável que executa as classes gramaticais.
     */ 
    private SearchCommands search;
    
    /**
     * Titulo do tipo de gráfico
     */
    private String name;
    /**
     * Descrição do gráfico - HELP
     */
    private String help;
        
    /** Armazena o gráfico que será colhido pela tela pai */
    private ChartPanel chartPanel;
    
    /**
     * Armazena um vetor/array de string referentes ao nome das unidades
     */
    private ArrayList<String> unitList;
    
    /**
     * Armazena todos os vetores/arrays de opções.
     * Cada vetor/array dentro de 'optionsList' tem seu primeiro elemento 
     * representando qual o nome/string da unidade a que as opções se refere.
     * -Exemplo: 
     * --Unidade: "Teste1"; Opções: "O1", "O2" e "O3";
     * --Unidade: "Teste2"; Opções: "O4", "O5" e "O6";
     * --- unitList: ["Teste1", "Teste2"];
     * --- optionsList: [["[UNIT]Teste1", "O1", "O2", "O3"], ["[UNIT]Teste2", "O4", "O5", "O6"]];
     */
    private ArrayList<ArrayList<String>> optionsList;
    
    /** 
     * Armazena qual unidade está ativada/selecionada
     * - Por 'default' a primeira de toda lista se torna selecionada
     */
    private String unitActive;
    
    /** 
     * Construtor 
     */
    public MoteLatency(){
        
        unitList = new ArrayList<>();
        optionsList = new ArrayList<>();
        
        name = "Mote Latency";
        help = "Help of Mote Latency";
        
        configUnitOptions();
        
        createGraph("");
    }
    
    /**
     * Configura todos os campos de unidades e de opções.
     * Realizando a ligação entre unidades e seus respectivos vetores de opções.
     */
    private void configUnitOptions(){

        // Adicionando as unidades
        unitList.add("Time Interval(15min)");
        unitList.add("Generic");
        unitList.add("Days");
        
        //Adicionando as opções
        //--Não existe definição de Opções
    }
        
    private void createGraph(String unit) {
        
        ArrayList<Object> answer;
        ArrayList<String> commands = new ArrayList<>();
        
        switch (unit){
            case "Time Interval(15min)":
                commands.add("ShowStatCur");
                commands.add("ShowStatShort");

                search = new SearchCommands(commands);
                answer = (ArrayList<Object>) search.getCommandsAnswer();

                ShowStatCur auxCur = ((ShowStatCur) ((ArrayList<Object>) answer.get(0)).get(0));
                ArrayList<ShowStatShort> auxShort = ((ArrayList<ShowStatShort>) answer.get(1));
                
                ArrayList<TimeSeries> timeSeriesList = new ArrayList<>();
                for(int j=0; j<auxShort.get(0).getidList().size(); j++){
                    TimeSeries timeSeries = new TimeSeries(auxShort.get(0).getidList().get(j));
                    timeSeriesList.add(timeSeries);
                }

                for(int i=0; i<timeSeriesList.size(); i++){
                    for(int k=0; k<auxShort.size(); k++){
                        for(int j=0; j<auxShort.get(k).getidList().size(); j++){
                            if((timeSeriesList.get(i).getKey().equals(auxShort.get(k).getidList().get(j))) && 
                                    (!auxShort.get(k).getlateList().get(j).equals("--"))){
                                String aux = auxShort.get(k).getlateList().get(j);
                                String[] aux1 = (auxShort.get(k).getHourFinal()).split(":");
                                String[] aux2 = (auxShort.get(k).getDataFinal()).split("/");
                                aux2[2] = "20" + aux2[2];

                                try{
                                    if((isNumber(aux1[2])) &&
                                        (isNumber(aux1[1])) &&
                                        (isNumber(aux1[0])) &&
                                        (isNumber(aux2[2])) &&
                                        (isNumber(aux2[1])) &&
                                        (isNumber(aux2[0])) &&
                                        (isNumber(aux))){
                                        
                                        timeSeriesList.get(i).add(new Second(
                                            Integer.valueOf(aux1[2]), 
                                            Integer.valueOf(aux1[1]), 
                                            Integer.valueOf(aux1[0]), 
                                            Integer.valueOf(aux2[1]), 
                                            Integer.valueOf(aux2[0]), 
                                            Integer.valueOf(aux2[2])), Double.valueOf(aux));
                                    }
                                } catch(SeriesException ex){
                                    System.out.println("[Erro] " + ex.toString());
                                }
                            }
                        }
                    }
                }

                TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();
                for(int i=0; i<timeSeriesList.size(); i++){
                    timeseriescollection.addSeries(timeSeriesList.get(i));
                }

                JFreeChart chart = ChartFactory.createTimeSeriesChart(name, "Time Interval(15min)", 
                        "Seconds", timeseriescollection, true, true, false);
                chart.setBackgroundPaint(Color.white);

                XYPlot xyplot = (XYPlot) chart.getPlot();
                //xyplot.setInsets(new RectangleInsets(0.0D, 0.0D, 0.0D, 20D));
                //ValueMarker valuemarker = new ValueMarker(700D);
                //valuemarker.setPaint(Color.blue);
                //valuemarker.setAlpha(0.8F);
                //xyplot.addRangeMarker(valuemarker);
                xyplot.setBackgroundPaint(null);
                //xyplot.setBackgroundImage(JFreeChart.INFO.getLogo());
                //xyplot.getDomainAxis().setLowerMargin(0.0D);
                xyplot.getDomainAxis().setVerticalTickLabels(true);
                
                chartPanel = new ChartPanel(chart);
                chartPanel.setBackground(Color.LIGHT_GRAY);
                chartPanel.setPreferredSize(new Dimension(700, 350)); 
                chartPanel.setDomainZoomable(false);
                chartPanel.setRangeZoomable(false);

                break;
            case "Generic":
                commands.add("ShowMote");

                search = new SearchCommands(commands);
                answer = (ArrayList<Object>) search.getCommandsAnswer();

                ArrayList<ShowMote> auxMote = ((ArrayList<ShowMote>) answer.get(0));

                DefaultCategoryDataset dataset2 = new DefaultCategoryDataset();
                for(int i=0; i< auxMote.size(); i++){
                    if (isNumber(auxMote.get(i).getLate())){
                        dataset2.addValue(Double.valueOf(auxMote.get(i).getLate()), 
                            "Devices", 
                            auxMote.get(i).getIdMote());
                    }
                }
                
                JFreeChart chart2 = ChartFactory.createBarChart(name, 
                        "", "Seconds", 
                        dataset2, PlotOrientation.VERTICAL, 
                        true, true, false);
                chart2.setBackgroundPaint(Color.white);

                CategoryPlot plot2 = (CategoryPlot) chart2.getPlot();
                plot2.setBackgroundPaint(Color.white);
                plot2.setDomainGridlinePaint(Color.white);
                plot2.setDomainGridlinesVisible(true);
                plot2.setRangeGridlinePaint(Color.white);
                
                chartPanel = new ChartPanel(chart2);
                chartPanel.setBackground(Color.LIGHT_GRAY);
                chartPanel.setPreferredSize(new Dimension(700, 350)); 
                chartPanel.setDomainZoomable(false);
                chartPanel.setRangeZoomable(false);

                break;
            case "Days":
                commands.add("ShowStatDay");

                search = new SearchCommands(commands);
                answer = (ArrayList<Object>) search.getCommandsAnswer();

                ArrayList<ShowStatDay> auxDay = ((ArrayList<ShowStatDay>) answer.get(0));
                
                DefaultCategoryDataset dataset = new DefaultCategoryDataset();
                for(int k=0; k<auxDay.size(); k++){
                    for(int j=0; j<auxDay.get(k).getidList().size(); j++){
                        String aux = auxDay.get(k).getlateList().get(j);
                        //if(!aux.equals("--")){
                        if (isNumber(aux)){
                            dataset.addValue(Float.valueOf(aux),
                                    "Day " + auxDay.get(k).getidDay(),
                                    auxDay.get(k).getidList().get(j));
                        }
                    }
                }

                JFreeChart chart3 = ChartFactory.createBarChart(name, 
                        "Devices",
                        "Seconds",
                        dataset,
                        PlotOrientation.VERTICAL,
                        true,
                        true,
                        false);
                chart3.setBackgroundPaint(Color.white);

                CategoryPlot plot = (CategoryPlot) chart3.getPlot();
                plot.setBackgroundPaint(Color.white);
                plot.setDomainGridlinePaint(Color.white);
                plot.setDomainGridlinesVisible(true);
                plot.setRangeGridlinePaint(Color.white);

                chartPanel = new ChartPanel(chart3);
                chartPanel.setBackground(Color.LIGHT_GRAY);
                chartPanel.setPreferredSize(new Dimension(700, 350));
                chartPanel.setDomainZoomable(false);
                chartPanel.setRangeZoomable(false);

                break;
            default:
                chartPanel = new ChartPanel(null);
                
                break;
        }
    }    
    
    /**
     * Verifica se o 'texto' é um número. Podendo ser inteiro ou float.
     * @param texto
     * @return 
     */
    public static boolean isNumber(String texto) {  
        if(texto == null) {
            return false;
        }  
        for (char letra : texto.toCharArray()) {
            if((letra < '0' || letra > '9') && (letra != '.')) {
                return false;
            }
        }  
        return true;  
        
    }
    
    @Override
    public String toString(){
        return name;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public ArrayList<String> getUnitList() {
        return unitList;
    }

    /**
     * Retorna o chartPanel 'default'
     * @return 
     */
    @Override
    public ChartPanel getChartPanel() {
        return chartPanel;
    }

    @Override
    public String getHelp() {
        return help;
    }

    @Override
    public ChartPanel getChartPanel(String unit) {
        for(int i=0; i<unitList.size(); i++){
            if(unit.equals(unitList.get(i))){
                createGraph(unit);
            }
        }
        return chartPanel;
    }

    @Override
    public ArrayList<String> getOptionsList(String unit) {
        ArrayList<String> auxReturn = new ArrayList<>();
        
        for(int i=0; i<optionsList.size(); i++){
            if((optionsList.get(i)).get(0).equals("[UNIT]" + unit)){
                
                for(int j=1; j<optionsList.size(); j++){
                    auxReturn.add(optionsList.get(i).get(j));
                }
            }
        }
        return auxReturn;
    }
    
}
